from datetime import datetime

from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.db.models import Q, Count
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from drf_spectacular.utils import extend_schema
from rest_framework import filters, status
from rest_framework.decorators import action
from rest_framework.response import Response

from apps.cbsp.filters import *
from apps.cbsp.models import *
from apps.cbsp.serializers import *
from apps.common.models import Pagination
from apps.data.schemas import DownloadResponse, UploadRequest, UploadResponse
from apps.pbi.permissions import CbspPermission
from apps.system.models import Workflow, User, Check, Dict_item, Company
from apps.system.serializers import WorkflowSerializer
from extensions.permissions import IsAuthenticated
from extensions.viewsets import *


class Cbsp_Bi_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """基本信息管理"""
    serializer_class = Cbsp_Bi_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_RecordsFilter
    search_fields = ['employee_number', 'name', 'sfz_number']
    select_related_fields = ['company', 'creator','employment_line','job_title','job_level','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        print(self.request.user)
        if "cbsp_view_all" not in self.request.user.permissions:

            base_query &= Q(company=self.request.user.company)

        cbsp_bi_record = Cbsp_Bi_Records.objects.filter(base_query)
        return cbsp_bi_record


    @action(detail=False, methods=['get'])
    def get_employee_number(self, request, *args, **kwargs):
        """employee_number"""
        employee_number = request.GET.get('employee_number', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records.objects.exclude(id=id).filter(employee_number=employee_number).exists()
        else:
            exists = Cbsp_Bi_Records.objects.filter(employee_number=employee_number).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def get_sfz_number(self, request, *args, **kwargs):
        """获取数据sfz_number"""
        sfz_number = request.GET.get('sfz_number', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records.objects.exclude(id=id).filter(sfz_number=sfz_number).exists()
        else:
            exists = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)


    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)
        

    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_record = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_record)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_record.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_record = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_record)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_record.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_record = self.get_object()
        # Set the new values
        cbsp_bi_record.step = request.data.get('step', cbsp_bi_record.step)
        cbsp_bi_record.is_effective = request.data.get('is_effective', cbsp_bi_record.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_record.next_checker = next_checker
        else:
            cbsp_bi_record.next_checker = None

        cbsp_bi_record.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_record)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_record.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_RecordsImportSerializer,"基本信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_RecordsImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_item in Cbsp_Bi_Records_items:
            employee_number = Cbsp_Bi_Records_item.get('employee_number', None)
            if not employee_number or not employee_number.isalnum():
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': '“员工编号”应该只包含字母和数字的组合'})
            # Check if `job_date` is a datetime object
            if isinstance(Cbsp_Bi_Records_item['job_date'], datetime):
                # Convert `job_date` to a date object
                Cbsp_Bi_Records_item['job_date'] = Cbsp_Bi_Records_item['job_date'].date()
            dict_items = ['employment_line', 'job_title', 'job_level']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_item.get(dict_item, None)
                Cbsp_Bi_Records_item[dict_item] = self.get_import_data_dict_instance(item)
            company = Cbsp_Bi_Records_item.get('company', None)
            Cbsp_Bi_Records_item['status'] = True if Cbsp_Bi_Records_item['status'].strip()=="在岗" else False
            Cbsp_Bi_Records_item['is_core'] = True if Cbsp_Bi_Records_item['is_core'].strip() == "是" else False
            Cbsp_Bi_Records_item['company'] = self.get_import_data_company_instance(company)
            Cbsp_Bi_Records_item['updater'] = self.user
            Cbsp_Bi_Records_item['step'] = 5
            Cbsp_Bi_Records_item['is_effective'] = 1
            cbsp_ci_record = Cbsp_Bi_Records.objects.filter(sfz_number=Cbsp_Bi_Records_item['sfz_number']).first()
            if cbsp_ci_record:
                #更新时间
                Cbsp_Bi_Records_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_ci_record.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records.objects.filter(sfz_number=Cbsp_Bi_Records_item['sfz_number']).update(del_flag=0,**Cbsp_Bi_Records_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_item['creator'] = self.user
                Cbsp_Bi_Records_item['id'] = Cbsp_Bi_Records().generate_unique_id()
                cbsp_ci_record = Cbsp_Bi_Records.objects.create(**Cbsp_Bi_Records_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的公司实例
    def get_import_data_company_instance(self, company):
        try:
            if company:
                return Company.objects.get(Q(name__icontains=company))
            else:
                return self.user.company
        except Company.DoesNotExist:
            return self.user.company

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_PersonnelViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """人员基础信息管理"""
    serializer_class = Cbsp_Bi_Records_PersonnelSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_PersonnelFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi','nation', 'marital_status','household_type','health_status','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_personnel = Cbsp_Bi_Records_Personnel.objects.filter(base_query)
        return cbsp_bi_records_personnel


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Personnel.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Personnel.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_personnel = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_personnel)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_personnel.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_personnel = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_personnel)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_personnel.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_personnel = self.get_object()
        # Set the new values
        cbsp_bi_records_personnel.step = request.data.get('step', cbsp_bi_records_personnel.step)
        cbsp_bi_records_personnel.is_effective = request.data.get('is_effective', cbsp_bi_records_personnel.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_personnel.next_checker = next_checker
        else:
            cbsp_bi_records_personnel.next_checker = None

        cbsp_bi_records_personnel.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_personnel)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_personnel.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Personnel.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Personnel.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Personnel.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_PersonnelImportSerializer,"人员基础信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_PersonnelImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Personnel_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Personnel_item in Cbsp_Bi_Records_Personnel_items:
            dict_items = ['nation', 'marital_status', 'household_type', 'health_status']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Personnel_item.get(dict_item, None)
                Cbsp_Bi_Records_Personnel_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Personnel_item['is_archiving'] = True if Cbsp_Bi_Records_Personnel_item['is_archiving'].strip()=="是" else False
            Cbsp_Bi_Records_Personnel_item['updater'] = self.user
            Cbsp_Bi_Records_Personnel_item['step'] = 5
            Cbsp_Bi_Records_Personnel_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Personnel_item['sfz_number']
            cbsp_bi_records_personnel = Cbsp_Bi_Records_Personnel.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取基本信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Personnel_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Personnel_item['cbsp_bi'] = cbsp_bi
            cbsp_bi_records_personnel.update_birthday_gender()
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Personnel_item.pop('employee_number', None)
            Cbsp_Bi_Records_Personnel_item.pop('name', None)
            Cbsp_Bi_Records_Personnel_item.pop('sfz_number')
            if cbsp_bi_records_personnel:
                #更新时间
                Cbsp_Bi_Records_Personnel_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_personnel.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Personnel.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Personnel_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Personnel_item['creator'] = self.user
                Cbsp_Bi_Records_Personnel_item['id'] = Cbsp_Bi_Records_Personnel().generate_unique_id()
                cbsp_bi_records_personnel = Cbsp_Bi_Records_Personnel.objects.create(**Cbsp_Bi_Records_Personnel_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_ContactViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_ContactSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_ContactFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'emergency_contact_relationship','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_contact = Cbsp_Bi_Records_Contact.objects.filter(base_query)
        return cbsp_bi_records_contact


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Contact.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Contact.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_contact = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_contact)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_contact.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_contact = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_contact)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_contact.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_contact = self.get_object()
        # Set the new values
        cbsp_bi_records_contact.step = request.data.get('step', cbsp_bi_records_contact.step)
        cbsp_bi_records_contact.is_effective = request.data.get('is_effective', cbsp_bi_records_contact.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_contact.next_checker = next_checker
        else:
            cbsp_bi_records_contact.next_checker = None

        cbsp_bi_records_contact.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_contact)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_contact.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Contact.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Contact.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Contact.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_ContactImportSerializer,"人员基础信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_ContactImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Contact_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Contact_item in Cbsp_Bi_Records_Contact_items:
            dict_items = ['emergency_contact_relationship']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Contact_item.get(dict_item, None)
                Cbsp_Bi_Records_Contact_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Contact_item['updater'] = self.user
            Cbsp_Bi_Records_Contact_item['step'] = 5
            Cbsp_Bi_Records_Contact_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Contact_item['sfz_number']
            cbsp_bi_records_contact = Cbsp_Bi_Records_Contact.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Contact_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Contact_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Contact_item.pop('employee_number', None)
            Cbsp_Bi_Records_Contact_item.pop('name', None)
            Cbsp_Bi_Records_Contact_item.pop('sfz_number')
            if cbsp_bi_records_contact:
                #更新时间
                Cbsp_Bi_Records_Contact_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_contact.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Contact.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Contact_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Contact_item['creator'] = self.user
                Cbsp_Bi_Records_Contact_item['id'] = Cbsp_Bi_Records_Contact().generate_unique_id()
                cbsp_bi_records_contact = Cbsp_Bi_Records_Contact.objects.create(**Cbsp_Bi_Records_Contact_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_Commercial_InsuranceViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_Commercial_InsuranceSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_Commercial_InsuranceFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'insurance_type','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_Records_commercial_insurance = Cbsp_Bi_Records_Commercial_Insurance.objects.filter(base_query)
        return cbsp_bi_Records_commercial_insurance


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Commercial_Insurance.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Commercial_Insurance.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_Records_commercial_insurance = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_Records_commercial_insurance)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_Records_commercial_insurance.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_Records_commercial_insurance = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_Records_commercial_insurance)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_Records_commercial_insurance.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_Records_commercial_insurance = self.get_object()
        # Set the new values
        cbsp_bi_Records_commercial_insurance.step = request.data.get('step', cbsp_bi_Records_commercial_insurance.step)
        cbsp_bi_Records_commercial_insurance.is_effective = request.data.get('is_effective', cbsp_bi_Records_commercial_insurance.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_Records_commercial_insurance.next_checker = next_checker
        else:
            cbsp_bi_Records_commercial_insurance.next_checker = None

        cbsp_bi_Records_commercial_insurance.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_Records_commercial_insurance)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_Records_commercial_insurance.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Commercial_Insurance.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Commercial_Insurance.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Commercial_Insurance.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_Commercial_InsuranceImportSerializer,"人员基础信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_Commercial_InsuranceImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Commercial_Insurance_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Commercial_Insurance_item in Cbsp_Bi_Records_Commercial_Insurance_items:
            dict_items = ['insurance_type']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Commercial_Insurance_item.get(dict_item, None)
                Cbsp_Bi_Records_Commercial_Insurance_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Commercial_Insurance_item['updater'] = self.user
            Cbsp_Bi_Records_Commercial_Insurance_item['step'] = 5
            Cbsp_Bi_Records_Commercial_Insurance_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Commercial_Insurance_item['sfz_number']
            cbsp_bi_Records_commercial_insurance = Cbsp_Bi_Records_Commercial_Insurance.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Commercial_Insurance_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Commercial_Insurance_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Commercial_Insurance_item.pop('employee_number', None)
            Cbsp_Bi_Records_Commercial_Insurance_item.pop('name', None)
            Cbsp_Bi_Records_Commercial_Insurance_item.pop('sfz_number')
            if cbsp_bi_Records_commercial_insurance:
                #更新时间
                Cbsp_Bi_Records_Commercial_Insurance_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_Records_commercial_insurance.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Commercial_Insurance.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Commercial_Insurance_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Commercial_Insurance_item['creator'] = self.user
                Cbsp_Bi_Records_Commercial_Insurance_item['id'] = Cbsp_Bi_Records_Commercial_Insurance().generate_unique_id()
                cbsp_bi_Records_commercial_insurance = Cbsp_Bi_Records_Commercial_Insurance.objects.create(**Cbsp_Bi_Records_Commercial_Insurance_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_Party_GroupViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_Party_GroupSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_Party_GroupFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'political_status','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_party_group = Cbsp_Bi_Records_Party_Group.objects.filter(base_query)
        return cbsp_bi_records_party_group


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Party_Group.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Party_Group.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_party_group = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_party_group)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_party_group.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_party_group = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_party_group)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_party_group.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_party_group = self.get_object()
        # Set the new values
        cbsp_bi_records_party_group.step = request.data.get('step', cbsp_bi_records_party_group.step)
        cbsp_bi_records_party_group.is_effective = request.data.get('is_effective', cbsp_bi_records_party_group.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_party_group.next_checker = next_checker
        else:
            cbsp_bi_records_party_group.next_checker = None

        cbsp_bi_records_party_group.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_party_group)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_party_group.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Party_Group.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Party_Group.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Party_Group.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_Party_GroupImportSerializer,"党群信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_Party_GroupImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Party_Group_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Party_Group_item in Cbsp_Bi_Records_Party_Group_items:
            dict_items = ['political_status']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Party_Group_item.get(dict_item, None)
                Cbsp_Bi_Records_Party_Group_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Party_Group_item['updater'] = self.user
            Cbsp_Bi_Records_Party_Group_item['step'] = 5
            Cbsp_Bi_Records_Party_Group_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Party_Group_item['sfz_number']
            Cbsp_Bi_Records_Party_Group_item['is_democratic_party'] = True if Cbsp_Bi_Records_Party_Group_item['is_democratic_party'].strip() == "是" else False
            cbsp_bi_records_party_group = Cbsp_Bi_Records_Party_Group.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Party_Group_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Party_Group_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Party_Group_item.pop('employee_number', None)
            Cbsp_Bi_Records_Party_Group_item.pop('name', None)
            Cbsp_Bi_Records_Party_Group_item.pop('sfz_number')
            if cbsp_bi_records_party_group:
                #更新时间
                Cbsp_Bi_Records_Party_Group_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_party_group.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Party_Group.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Party_Group_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Party_Group_item['creator'] = self.user
                Cbsp_Bi_Records_Party_Group_item['id'] = Cbsp_Bi_Records_Party_Group().generate_unique_id()
                cbsp_bi_records_party_group = Cbsp_Bi_Records_Party_Group.objects.create(**Cbsp_Bi_Records_Party_Group_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_SkillViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_SkillSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_SkillFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'driving_license_type','employment_line','star_rating','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_skill = Cbsp_Bi_Records_Skill.objects.filter(base_query)
        return cbsp_bi_records_skill


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Skill.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Skill.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_skill = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_skill)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_skill.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_skill = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_skill)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_skill.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_skill = self.get_object()
        # Set the new values
        cbsp_bi_records_skill.step = request.data.get('step', cbsp_bi_records_skill.step)
        cbsp_bi_records_skill.is_effective = request.data.get('is_effective', cbsp_bi_records_skill.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_skill.next_checker = next_checker
        else:
            cbsp_bi_records_skill.next_checker = None

        cbsp_bi_records_skill.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_skill)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_skill.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Skill.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Skill.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Skill.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_SkillImportSerializer,"技能信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_SkillImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Skill_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Skill_item in Cbsp_Bi_Records_Skill_items:
            dict_items = ['driving_license_type','employment_line','star_rating']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Skill_item.get(dict_item, None)
                Cbsp_Bi_Records_Skill_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Skill_item['updater'] = self.user
            Cbsp_Bi_Records_Skill_item['step'] = 5
            Cbsp_Bi_Records_Skill_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Skill_item['sfz_number']
            Cbsp_Bi_Records_Skill_item['is_driving_license'] = True if Cbsp_Bi_Records_Skill_item['is_driving_license'].strip() == "是" else False
            Cbsp_Bi_Records_Skill_item['is_professional_driver'] = True if Cbsp_Bi_Records_Skill_item['is_professional_driver'].strip() == "是" else False
            cbsp_bi_records_skill = Cbsp_Bi_Records_Skill.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()

            #如果Cbsp_Bi_Records_Skill_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Skill_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Skill_item.pop('employee_number', None)
            Cbsp_Bi_Records_Skill_item.pop('name', None)
            Cbsp_Bi_Records_Skill_item.pop('sfz_number')
            if cbsp_bi_records_skill:
                #更新时间
                Cbsp_Bi_Records_Skill_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_skill.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Skill.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Skill_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Skill_item['creator'] = self.user
                Cbsp_Bi_Records_Skill_item['id'] = Cbsp_Bi_Records_Skill().generate_unique_id()
                cbsp_bi_records_skill = Cbsp_Bi_Records_Skill.objects.create(**Cbsp_Bi_Records_Skill_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_Personal_FinanceViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_Personal_FinanceSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_Personal_FinanceFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'medical_insurance_type','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_personal_finance = Cbsp_Bi_Records_Personal_Finance.objects.filter(base_query)
        return cbsp_bi_records_personal_finance


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Personal_Finance.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Personal_Finance.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_personal_finance = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_personal_finance)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_personal_finance.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_personal_finance = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_personal_finance)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_personal_finance.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_personal_finance = self.get_object()
        # Set the new values
        cbsp_bi_records_personal_finance.step = request.data.get('step', cbsp_bi_records_personal_finance.step)
        cbsp_bi_records_personal_finance.is_effective = request.data.get('is_effective', cbsp_bi_records_personal_finance.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_personal_finance.next_checker = next_checker
        else:
            cbsp_bi_records_personal_finance.next_checker = None

        cbsp_bi_records_personal_finance.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_personal_finance)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_personal_finance.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Personal_Finance.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Personal_Finance.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Personal_Finance.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_Personal_FinanceImportSerializer,"社保等个人金融信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_Personal_FinanceImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Personal_Finance_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Personal_Finance_item in Cbsp_Bi_Records_Personal_Finance_items:
            dict_items = ['medical_insurance_type']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Personal_Finance_item.get(dict_item, None)
                Cbsp_Bi_Records_Personal_Finance_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Personal_Finance_item['updater'] = self.user
            Cbsp_Bi_Records_Personal_Finance_item['step'] = 5
            Cbsp_Bi_Records_Personal_Finance_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Personal_Finance_item['sfz_number']
            Cbsp_Bi_Records_Personal_Finance_item['is_medical_insurance_card'] = True if Cbsp_Bi_Records_Personal_Finance_item[
                                                                           'is_medical_insurance_card'].strip() == "是" else False
            cbsp_bi_records_personal_finance = Cbsp_Bi_Records_Personal_Finance.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Personal_Finance_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Personal_Finance_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Personal_Finance_item.pop('employee_number', None)
            Cbsp_Bi_Records_Personal_Finance_item.pop('name', None)
            Cbsp_Bi_Records_Personal_Finance_item.pop('sfz_number')
            if cbsp_bi_records_personal_finance:
                #更新时间
                Cbsp_Bi_Records_Personal_Finance_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_personal_finance.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Personal_Finance.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Personal_Finance_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Personal_Finance_item['creator'] = self.user
                Cbsp_Bi_Records_Personal_Finance_item['id'] = Cbsp_Bi_Records_Personal_Finance().generate_unique_id()
                cbsp_bi_records_personal_finance = Cbsp_Bi_Records_Personal_Finance.objects.create(**Cbsp_Bi_Records_Personal_Finance_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_EducationViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_EducationSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_EducationFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'medical_insurance_type','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_education = Cbsp_Bi_Records_Education.objects.filter(base_query)
        return cbsp_bi_records_education


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Education.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Education.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_education = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_education)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_education.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_education = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_education)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_education.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_education = self.get_object()
        # Set the new values
        cbsp_bi_records_education.step = request.data.get('step', cbsp_bi_records_education.step)
        cbsp_bi_records_education.is_effective = request.data.get('is_effective', cbsp_bi_records_education.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_education.next_checker = next_checker
        else:
            cbsp_bi_records_education.next_checker = None

        cbsp_bi_records_education.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_education)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_education.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Education.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Education.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Education.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_EducationImportSerializer,"学历信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_EducationImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Education_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Education_item in Cbsp_Bi_Records_Education_items:
            dict_items = ['highest_education','highest_education_way','bachelor_degree_level','bachelor_degree_type']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Education_item.get(dict_item, None)
                Cbsp_Bi_Records_Education_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Education_item['updater'] = self.user
            Cbsp_Bi_Records_Education_item['step'] = 5
            Cbsp_Bi_Records_Education_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Education_item['sfz_number']
            Cbsp_Bi_Records_Education_item['is_full_time'] = True if Cbsp_Bi_Records_Education_item[
                                                                           'is_full_time'].strip() == "是" else False
            Cbsp_Bi_Records_Education_item['is_education_verification'] = True if Cbsp_Bi_Records_Education_item[
                                                                           'is_education_verification'].strip() == "是" else False
            Cbsp_Bi_Records_Education_item['is_bachelor_degree'] = True if Cbsp_Bi_Records_Education_item[
                                                                           'is_bachelor_degree'].strip() == "是" else False
            cbsp_bi_records_education = Cbsp_Bi_Records_Education.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Education_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Education_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Education_item.pop('employee_number', None)
            Cbsp_Bi_Records_Education_item.pop('name', None)
            Cbsp_Bi_Records_Education_item.pop('sfz_number')
            if cbsp_bi_records_education:
                #更新时间
                Cbsp_Bi_Records_Education_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_education.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Education.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Education_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Education_item['creator'] = self.user
                Cbsp_Bi_Records_Education_item['id'] = Cbsp_Bi_Records_Education().generate_unique_id()
                cbsp_bi_records_education = Cbsp_Bi_Records_Education.objects.create(**Cbsp_Bi_Records_Education_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_WorkViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """联系信息管理"""
    serializer_class = Cbsp_Bi_Records_WorkSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_WorkFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'medical_insurance_type','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_work = Cbsp_Bi_Records_Work.objects.filter(base_query)
        return cbsp_bi_records_work


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Work.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Work.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_work = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_work)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_work.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_work = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_work)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_work.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_work = self.get_object()
        # Set the new values
        cbsp_bi_records_work.step = request.data.get('step', cbsp_bi_records_work.step)
        cbsp_bi_records_work.is_effective = request.data.get('is_effective', cbsp_bi_records_work.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_work.next_checker = next_checker
        else:
            cbsp_bi_records_work.next_checker = None

        cbsp_bi_records_work.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_work)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_work.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Work.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Work.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Work.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_WorkImportSerializer,"工作信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_WorkImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Work_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Work_item in Cbsp_Bi_Records_Work_items:
            dict_items = ['employment_source', 'full_part_time_driver_safety_officer']
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Work_item.get(dict_item, None)
                Cbsp_Bi_Records_Work_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Work_item['updater'] = self.user
            Cbsp_Bi_Records_Work_item['step'] = 5
            Cbsp_Bi_Records_Work_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Work_item['sfz_number']
            is_items=['is_entry_training','is_entry_training_assessment','is_full_time','on_job_status','is_entry_physical_examination',
                        'is_full_part_time','is_resignation_procedures','is_labor_social_security_notice'
                      ]
            for is_item in is_items:
                if is_item=='on_job_status':
                    Cbsp_Bi_Records_Work_item[is_item] = True if Cbsp_Bi_Records_Work_item[
                                                                     is_item].strip() == "在职" else False
                else:
                    Cbsp_Bi_Records_Work_item[is_item] = True if Cbsp_Bi_Records_Work_item[is_item].strip() == "是" else False

            cbsp_bi_records_work = Cbsp_Bi_Records_Work.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Work_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Work_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Work_item.pop('employee_number', None)
            Cbsp_Bi_Records_Work_item.pop('name', None)
            Cbsp_Bi_Records_Work_item.pop('sfz_number')
            if cbsp_bi_records_work:
                #更新时间
                Cbsp_Bi_Records_Work_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_work.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Work.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Work_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Work_item['creator'] = self.user
                Cbsp_Bi_Records_Work_item['id'] = Cbsp_Bi_Records_Work().generate_unique_id()
                cbsp_bi_records_work = Cbsp_Bi_Records_Work.objects.create(**Cbsp_Bi_Records_Work_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Cbsp_Bi_Records_CertificateViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """证书信息管理"""
    serializer_class = Cbsp_Bi_Records_CertificateSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, CbspPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Cbsp_Bi_Records_CertificateFilter
    search_fields = ['cbsp_bi__employee_number', 'cbsp_bi__name', 'cbsp_bi__sfz_number']
    select_related_fields = ['cbsp_bi', 'medical_insurance_type','creator','updater','next_checker']
    ordering_fields = ['id','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return cbsp_bi_record.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "cbsp_view_all" not in self.request.user.permissions:
            base_query &= Q(cbsp_bi__company=self.request.user.company)

        cbsp_bi_records_certificate = Cbsp_Bi_Records_Certificate.objects.filter(base_query)
        return cbsp_bi_records_certificate


    @action(detail=False, methods=['get'])
    def get_cbsp_bi(self, request, *args, **kwargs):
        """cbsp_bi"""
        cbsp_bi = request.GET.get('cbsp_bi', None)
        id = request.GET.get('id', None)
        #如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Cbsp_Bi_Records_Certificate.objects.exclude(id=id).filter(cbsp_bi=cbsp_bi).exists()
        else:
            exists = Cbsp_Bi_Records_Certificate.objects.filter(cbsp_bi=cbsp_bi).exists()
        return Response(data={'exists': exists}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Cbsp_Bi_Records').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        cbsp_bi_records_certificate = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_certificate)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_certificate.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的基本信息对象
        original_cbsp_bi_record= self.get_object()
        # 保存更新后的基本信息对象
        cbsp_bi_records_certificate = serializer.save()
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_certificate)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_certificate.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        cbsp_bi_records_certificate = self.get_object()
        # Set the new values
        cbsp_bi_records_certificate.step = request.data.get('step', cbsp_bi_records_certificate.step)
        cbsp_bi_records_certificate.is_effective = request.data.get('is_effective', cbsp_bi_records_certificate.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            cbsp_bi_records_certificate.next_checker = next_checker
        else:
            cbsp_bi_records_certificate.next_checker = None

        cbsp_bi_records_certificate.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(cbsp_bi_records_certificate)
        Check.objects.create(
            content_type=content_type, object_id=cbsp_bi_records_certificate.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Cbsp_Bi_Records_Certificate.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Certificate.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Cbsp_Bi_Records_Certificate.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('id')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Cbsp_Bi_Records_CertificateImportSerializer,"证书信息导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Cbsp_Bi_Records_CertificateImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Cbsp_Bi_Records_Certificate_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        del_flag_changed_count = 0  # Add a new counter variable
        for Cbsp_Bi_Records_Certificate_item in Cbsp_Bi_Records_Certificate_items:
            dict_items = []
            for dict_item in dict_items:
                item= Cbsp_Bi_Records_Certificate_item.get(dict_item, None)
                Cbsp_Bi_Records_Certificate_item[dict_item] = self.get_import_data_dict_instance(item)
            Cbsp_Bi_Records_Certificate_item['updater'] = self.user
            Cbsp_Bi_Records_Certificate_item['step'] = 5
            Cbsp_Bi_Records_Certificate_item['is_effective'] = 1
            sfz_number= Cbsp_Bi_Records_Certificate_item['sfz_number']
            is_items=[
                'is_electrician_certificate','is_review_electrician_certificate',
                'is_high_altitude_certificate','is_review_high_altitude_certificate',
                'is_line_certificate','is_review_line_certificate',
                'is_mobile_maintenance_qualification_certification',
                      ]
            for is_item in is_items:
                print(Cbsp_Bi_Records_Certificate_item.get(is_item, ""))
                Cbsp_Bi_Records_Certificate_item[is_item] = True if Cbsp_Bi_Records_Certificate_item.get(is_item, "").strip() == "是" else False

            cbsp_bi_records_certificate = Cbsp_Bi_Records_Certificate.objects.filter(cbsp_bi__sfz_number=sfz_number).first()
            #获取联系信息实例
            cbsp_bi = Cbsp_Bi_Records.objects.filter(sfz_number=sfz_number).first()
            #如果Cbsp_Bi_Records_Certificate_item['cbsp_bi']为空，则返回错误信息
            if not cbsp_bi:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "身份证号码为“{}”的人员基本信息不存在".format(sfz_number)})
            else:
                Cbsp_Bi_Records_Certificate_item['cbsp_bi'] = cbsp_bi
            #将employee_number、name、sfz_number移除,employee_number、name导入数据中可以不填写
            Cbsp_Bi_Records_Certificate_item.pop('employee_number', None)
            Cbsp_Bi_Records_Certificate_item.pop('name', None)
            Cbsp_Bi_Records_Certificate_item.pop('sfz_number')
            if cbsp_bi_records_certificate:
                #更新时间
                Cbsp_Bi_Records_Certificate_item['update_time'] = timezone.make_aware(datetime.now())
                if cbsp_bi_records_certificate.del_flag == 1:
                    del_flag_changed_count += 1
                Cbsp_Bi_Records_Certificate.objects.filter(cbsp_bi__sfz_number=sfz_number).update(del_flag=0,**Cbsp_Bi_Records_Certificate_item)
                update_count += 1
            else:
                Cbsp_Bi_Records_Certificate_item['creator'] = self.user
                Cbsp_Bi_Records_Certificate_item['id'] = Cbsp_Bi_Records_Certificate().generate_unique_id()
                cbsp_bi_records_certificate = Cbsp_Bi_Records_Certificate.objects.create(**Cbsp_Bi_Records_Certificate_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         'del_flag_changed_count': del_flag_changed_count
                                                         })

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        try:
            if dict_item:
                instance=Dict_item.objects.get(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item))
                return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None
